﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TA.JSON;

namespace TA.Turbo.Controls
{
	public abstract class BaseRepeaterEntries<T> : List<T>, IRepeaterEntries
	{
		#region PUBLIC
		#region INIT
		public BaseRepeaterEntries()
		{
		}
		public BaseRepeaterEntries(BaseRepeaterEntries<T> source)
		{
			this.AddRange(source);
		}
		#endregion
		#region EVENTS
		//public event EventHandler<SerializeEventArgs> SerializeEntry;
		//public event EventHandler<DeserializeEventArgs> DeserializeEntry;
		#endregion
		#region PROPS
		public RepeaterValue Owner
		{
			set
			{
				this._owner = value;
			}
		}
		public Repeater Repeater
		{
			get
			{
				if (this._repeater != null)
					return this._repeater;

				if (this._owner != null)
					return this._owner._owner;

				return null;
			}
			set
			{
				this._repeater = value;
			}
		}
		#endregion
		#region METHODS
		public abstract object Clone();
		public abstract object GetValue(int iEntry, string propertyPath);
		#endregion
		#endregion
		#region INTERNAL
		#region CONST/STATIC
		#endregion
		#region VARS
		RepeaterValue _owner;
		Repeater _repeater;
		#endregion
		#region PROPS
		#endregion
		#region METHODS
		#region INIT
		#endregion
		#region DATA
		#endregion
		#region HANDLERS
		#endregion
		#endregion
		#endregion
		#region JSON
		public bool IsDirty
		{
			get
			{
				return true;
			}
		}
		public void Serialize(JsonWriter jw)
		{
			this.SerializeArray(jw);
		}
		public void SerializeContents(JsonWriter jw)
		{
			if (this.Repeater.Fields.Count > 0)
			{
				foreach (T entry in this)
				{
					this.DoSerializeEntry(jw, entry);
				}
			}
			else
			{
				SerializeEventArgs sea = new SerializeEventArgs(jw, null);
				foreach (T entry in this)
				{
					sea.Entry = entry;
					this.Repeater.OnSerialize(sea);
				}
			}
		}
		protected abstract void DoSerializeEntry(JsonWriter jw, T entry);
		public void Deserialize(IJsonReader jr)
		{
			this.DeserializeArray(jr);
		}
		public void DeserializeContent(IJsonReader jr, string propShortName)
		{
			T entry = (T)this.Repeater.GetEmptyEntry();

			if (this.Repeater.Fields.Count > 0)
			{
				this.DoDeserializeEntry(jr, entry);
			}
			else
			{
				DeserializeEventArgs sea = new DeserializeEventArgs(jr, entry);
				this.Repeater.OnDeserialize(sea);
			}

			this.Add(entry);
		}

		protected abstract void DoDeserializeEntry(IJsonReader jr, T entry);
		#endregion
	}
}
